import React, { useState } from 'react';
import { Snackbar, Box } from '@mui/material';
import Menu from '@metacell/geppetto-meta-ui/menu/Menu';
import { useAppSelector, useAppDispatch } from '../../redux/hooks';
import { closeTopbarDialog, openTopbarDialog } from '../../redux/slices/topbarSlice';
import {
  openConfirmationDialog,
  openDialog,
  loadTutorial,
  createAndSimulateNetwork,
  createNetwork,
  simulateNetwork,
  editModel,
  showNetwork,
} from '../../redux/slices/generalSlice';
import { closeLaunchDialog, openLaunchDialog } from '../../redux/slices/experimentsSlice';
import { bgRegular } from '../../theme';
import { TOPBAR_CONSTANTS, NETPYNE_COMMANDS, MODEL_STATE, DEFAULT_CONFIRMATION_DIALOG_MESSAGE, LOAD_TUTORIAL } from '../../constants';
import Splash from '../general/Splash';
import SwitchPageButton from './SwitchPageButton';
import FileBrowser from '../general/FileBrowser';
import toolbarConfig, {
  getModelMenu,
  getTutorials,
  getViewMenu,
  getNetPyNEMenu,
} from './menuConfiguration';
import { startTutorial } from '../../redux/slices/tutorialsSlice';

// Import migrated dialogs
import {
  NewModelDialog,
  LoadFileDialog,
  SaveFileDialog,
  ImportFileDialog,
  LoadFileIndexDialog,
  OverwriteModelDialog,
  LaunchDialog,
  ImportExportHLSDialog,
  ImportCellParamsDialog,
  UploadDownloadFilesDialog,
} from './dialogs';

const Topbar: React.FC = () => {
  const [openSnackBar, setOpenSnackBar] = useState(false);
  const [snackBarMessage, setSnackBarMessage] = useState('');
  const dispatch = useAppDispatch();
  
  const state = useAppSelector((state: any) => state);
  const {
    dialogOpen,
    dialogName,
    dialogMetadata,
    modelState,
    modelLoaded,
    experimentInDesign,
    openLaunchDialog,
    inDesign,
  } = useAppSelector((state: any) => ({
    dialogOpen: state.topbar.dialogOpen,
    dialogName: state.topbar.dialogName,
    dialogMetadata: state.topbar.dialogMetadata,
    modelState: state.general.modelState,
    modelLoaded: state.client?.model?.status || false,
    experimentInDesign: state.experiments.inDesign != null,
    openLaunchDialog: state.experiments.openLaunchDialog,
    inDesign: state.experiments.inDesign,
  }));

  const handleClose = (): void => {
    dispatch(closeTopbarDialog());
  };

  const handleOpenSnackBar = (message: string): void => {
    setSnackBarMessage(message);
    setOpenSnackBar(true);
  };

  // Menu handler - handles all menu actions
  const menuHandler = (click: any): any => {
    if (!click) {
      return;
    }

    switch (click.handlerAction) {
      case 'redux': {
        const [action, payload] = click.parameters;
        if (payload !== undefined) {
          dispatch(action(payload));
        } else {
          dispatch(action());
        }
        break;
      }
      case TOPBAR_CONSTANTS.NEW_PAGE: {
        const [url] = click.parameters;
        window.open(url, '_blank');
        break;
      }
      case 'menuInjector': {
        const [menuName] = click.parameters;
        if (menuName === 'Model') {
          return getModelMenu({
            experimentInDesign,
            modelState,
          });
        }
        if (menuName === 'Tutorials') {
          return getTutorials();
        }
        if (menuName === 'View') {
          return getViewMenu({
            editMode: state.general.editMode,
            automaticInstantiation: state.general.automaticInstantiation,
            automaticSimulation: state.general.automaticSimulation,
          });
        }
        if (menuName === 'NetPYNE') {
          return getNetPyNEMenu({
            theme: state.general.theme,
          });
        }
        break;
      }
      case 'handleTutorial': {
        const [action, payload] = click.parameters;
        if (modelState === MODEL_STATE.INSTANTIATED || modelState === MODEL_STATE.SIMULATED) {
          dispatch(
            openConfirmationDialog({
              title: 'Warning',
              message: DEFAULT_CONFIRMATION_DIALOG_MESSAGE,
              onConfirm: {
                type: LOAD_TUTORIAL,
                action,
                payload,
              },
            }),
          );
        } else if (payload !== undefined) {
          dispatch(action(payload));
        } else {
          dispatch(action());
        }
        break;
      }
      case 'triggerTutorials': {
        const [index] = click.parameters;
        // Tutorial steps would need to be imported from data files
        // For now, we'll handle this via a placeholder
        // TODO: Import tutorial steps (tutorial_steps, tutorial2_steps, tutorial3_steps)
        // and dispatch startTutorial(tutorials[index])
        console.log('Tutorial triggered:', index);
        break;
      }
      default:
        console.log(`Menu action not mapped:`, click);
    }
  };

  const resetModel = (): void => {
    handleClose();
    // dispatch(resetModel()); // Will be implemented when needed
  };

  // Dialog content rendering - integrated with migrated dialogs
  const renderDialogContent = (): React.ReactNode => {
    if (!dialogOpen) {
      return null;
    }

    switch (dialogName) {
      case TOPBAR_CONSTANTS.LOAD:
        return (
          <LoadFileDialog
            open={dialogOpen}
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.SAVE_INDEX_WORKSPACE:
        return (
          <OverwriteModelDialog
            open={dialogOpen}
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.LOAD_INDEX_WORKSPACE:
        return (
          <FileBrowser
            open={dialogOpen}
            exploreOnlyDirs={true}
            startDir=""
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.LOAD_INDEX:
        return (
          <LoadFileIndexDialog
            open={dialogOpen}
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.SAVE:
        return (
          <SaveFileDialog
            open={dialogOpen}
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.IMPORT_NEUROML:
        return (
          <ImportFileDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            title="Import from NeuroML 2"
            command={NETPYNE_COMMANDS.importNeuroML}
            modelState={modelState}
            extension=".net.nml"
            openConfirmationDialog={(payload) => dispatch(openConfirmationDialog(payload))}
          />
        );
      case TOPBAR_CONSTANTS.IMPORT_LEMS:
        return (
          <ImportFileDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            command={NETPYNE_COMMANDS.importLEMS}
            title="Import simulation from LEMS"
            modelState={modelState}
            extension=".xml"
            openConfirmationDialog={(payload) => dispatch(openConfirmationDialog(payload))}
          />
        );
      case TOPBAR_CONSTANTS.NEW_MODEL:
        return (
          <NewModelDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            onAction={resetModel}
          />
        );
      case TOPBAR_CONSTANTS.IMPORT_HLS:
        return (
          <ImportExportHLSDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            mode="IMPORT"
            modelState={modelState}
            openConfirmationDialog={(payload) => dispatch(openConfirmationDialog(payload))}
          />
        );
      case TOPBAR_CONSTANTS.EXPORT_HLS:
        return (
          <ImportExportHLSDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            mode="EXPORT"
            modelState={modelState}
          />
        );
      case TOPBAR_CONSTANTS.IMPORT_CELL_TEMPLATE:
        return (
          <ImportCellParamsDialog
            open={dialogOpen}
            cellRuleName={dialogMetadata?.cellRuleName || ''}
            onRequestClose={handleClose}
          />
        );
      case TOPBAR_CONSTANTS.UPLOAD_FILES:
        return (
          <UploadDownloadFilesDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            openSnackBar={handleOpenSnackBar}
            mode="UPLOAD"
          />
        );
      case TOPBAR_CONSTANTS.DOWNLOAD_FILES:
        return (
          <UploadDownloadFilesDialog
            open={dialogOpen}
            onRequestClose={handleClose}
            openSnackBar={handleOpenSnackBar}
            mode="DOWNLOAD"
          />
        );
      default:
        return null;
    }
  };

  // Render LaunchDialog separately (managed by experiments slice)
  const renderLaunchDialog = (): React.ReactNode => {
    if (!openLaunchDialog || !inDesign) {
      return null;
    }
    return (
      <LaunchDialog
        open={openLaunchDialog}
        experimentName={inDesign.name}
        numberOfTrials={inDesign.trials?.length || 0}
        onRequestClose={() => dispatch(closeLaunchDialog())}
      />
    );
  };

  return (
    <>
      <Box
        sx={{
          backgroundColor: bgRegular,
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        <Menu configuration={toolbarConfig} menuHandler={menuHandler} />
        <Box>
          <SwitchPageButton />
        </Box>
      </Box>
      {!modelLoaded && <Splash />}
      <Snackbar
        message={snackBarMessage}
        autoHideDuration={4000}
        open={openSnackBar}
        onClose={() => setOpenSnackBar(false)}
      />
      {renderDialogContent()}
      {renderLaunchDialog()}
    </>
  );
};

export default Topbar;
